<?php
/*
 * session入库
 */
class SessionLib{
    private $db;    //保存数据库连接对象
    //实例化SessionLib类的时候就自动实现session入库
    public function __construct(){
        $this->initSession();
    }
    private function initSession(){
        //更改了session的存储
        session_set_save_handler(
            array($this,'open'),
            array($this,'close'),
            array($this,'read'),
            array($this,'write'),
            array($this,'destroy'),
            array($this,'gc')
        );
        @session_start();   //开启会话
    }
    //打开会话
    public function open() {
	$this->db=  MySQLDB::getInstance($GLOBALS['config']['database']);
    }
    //关闭会话
    public function close() {
        return true;
    }
    /**
    *读取会话
    *@param $sess_id char 会话编号
    */
    public function read($sess_id) {
            $sql="select sess_value from session where sess_id='$sess_id'";
            return $this->db->fetchColumn($sql);
    }
    /**
    *写会话
    *@param $sess_id char 会话编号
    *@param $sess_value varchar  序列化以后的会话字符串
    */
    public function write($sess_id,$sess_value) {
            $time=time();
            $sql="insert into session values ('$sess_id','$sess_value',$time) on duplicate key update sess_value='$sess_value'";	//没有会话就插入，存在会话就更新
            return $this->db->query($sql);
    }
    /**
    *销毁当前自己的会话
    @param $sess_id char 会话编号
    */
    public function destroy($sess_id) {
            $sql="delete from session where sess_id='$sess_id'";
            return $this->db->query($sql);
    }
    /**
    *垃圾回收
    *@param lifetime int 会话过期时间
    */
    public function gc($lifetime) {
            $time=time()-$lifetime;		//会话过期的临界值
            $sql="delete from session where sess_expires<$time";
           return $this->db->query($sql);
    }
}
